<?php
namespace frontend\models;

use Yii;
use yii\base\Model;
use yii\db\Connection;
use yii\db\Query;
use common\models\User;

class PageNavi extends Model
{

    public $offset;
    public $limit;
    public $count;

    public $current;
    public $start;
    public $end;
    public $pageTotal;

    public $urlTarget;

    public function initParams($limit, $count, $urlTarget) {
        $this->limit = $limit;
        $this->count = $count;
        $this->urlTarget = $urlTarget;

        $this->current = 1;
        $paramsGet = Yii::$app->request->get();
        if($paramsGet !== null) {
            $paramP = @$paramsGet['p'];
            if($paramP !== null) {
                $this->current = intval($paramP);
            }
        }

        $pageTotalCount = floor($count / $limit);
        if($count % $limit > 0) {
            $pageTotalCount++;
        }
        $this->pageTotal = $pageTotalCount;
        if($this->current > $pageTotalCount || $this->current < 1) {
            $this->current = 1;
        }
        $this->offset = ($this->current - 1) * $this->limit;
        $this->start = $this->current;
        $this->end = $this->current;


        $moveTotalCount = 5;
        $moveShowCount = $moveTotalCount;
        $moveHalfCount = floor($moveTotalCount / 2);
        $moveIndex = 1;
        for(; $moveIndex <= $moveHalfCount; $moveIndex++) {
            if($this->end + 1 <= $pageTotalCount) {
                $this->end++;
            } else {
                break;
            }
        }
        $moveShowCount -= $moveIndex - 1;
        $moveHalfCount = floor($moveTotalCount / 2);
        $moveIndex = 1;
        for(; $moveIndex <= $moveHalfCount; $moveIndex++) {
            if($this->start - 1 >= 1) {
                $this->start--;
            } else {
                break;
            }
        }
        $moveShowCount -= $moveIndex - 1;

        for($i = 0; $i < $moveShowCount; $i++) {
            if($this->end + 1 <= $pageTotalCount) {
                $this->end++;
            } else {
                break;
            }
        }
        for($i = 0; $i < $moveShowCount; $i++) {
            if($this->start - 1 >= 1) {
                $this->start--;
            } else {
                break;
            }
        }
    }

    public function hasMorePage() {
        if(($this->current > $this->start)
                || ($this->current < $this->end)) {
            return true;
        }
        return false;
    }

    public function getPageUrl($page) {
        if(strpos($this->urlTarget, '?') > 0) {
            return $this->urlTarget . "&p=" . $page;
        } else {
            return $this->urlTarget . "?p=" . $page;
        }
    }

}
